package com.qf.j2112.config;


import com.qf.j2112.po.Order;
import com.qf.j2112.po.OrderItem;
import com.qf.j2112.po.SysLog;
import com.qf.j2112.po.TourArea;
import com.qf.j2112.service.OrderService;
import com.qf.j2112.service.SysLogService;
import com.qf.j2112.service.TourAreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @ClassName MySchdule
 * @Description TODO
 * @Author jeffrey
 * @Date 2022/3/16 11:23
 * @Version 1.0
 **/
@Slf4j
@Configuration  //声明配置
@EnableScheduling  //开启定时任务服务
public class MySchdule {

    @Autowired
    private OrderService orderService;

    @Autowired
    private TourAreaService tourAreaService;

    @Autowired
    private SysLogService sysLogService;

    @Transactional
    @Scheduled(cron ="0 */10 * * * ?")  //每10分钟触发一次
    public  void  doOrderInvalid(){

        //查询订单表
        List<Order> unpaidOrders= orderService.findUnpaidOrder();
        int count=0;
        for(Order o:unpaidOrders){
            Date date= o.getCreateTime();
            //大于5分钟超时
            //创建时间超过30‘的订单，将其状态置为（订单失效）过期 2
            if (System.currentTimeMillis()-date.getTime()>=OrderConfig.overTimeMinute*60*1000){
                orderService.doOrderInvalid(o);
                SysLog sysLog=new SysLog(0,000,"系统","使订单"+o.getOrderId()+"失效",new Date(),"0.0.0.0");
                log.info(new Date().toLocaleString()+"系统使订单"+o.getOrderId()+"失效");
                sysLogService.addSysLog(sysLog);

                //2. 还库存（把失效订单占用的库存数量还回库存中，继续销售）
                List<OrderItem> orderItems = orderService.findAllOrderItem(o.getOrderId());
                for (OrderItem i:orderItems){
                    TourArea tourArea=tourAreaService.findOneByAid(i.getA_id());
                    //原库存加上订单详情里的数量
                    tourArea.setCount(tourArea.getCount()+i.getItem_num());
                    tourArea.setRefreshTime(new Date());
                    //更新数据库
                    tourAreaService.updateTourArea(tourArea);
                    log.info(new Date().toLocaleString()+"归还了"+tourArea.getAname()+"的"+i.getItem_num()+"个库存");
                    SysLog sysLog1=new SysLog(0,000,"系统","归还了"+tourArea.getAname()+"的"+i.getItem_num()+"个库存",new Date(),"0.0.0.0");
                    sysLogService.addSysLog(sysLog1);
                }
                count++;
            }
        }
        System.out.println(new Date().toLocaleString()+":本次共使"+count+"个订单失效");
    }
}
